<template>
  <div>
    <el-card shadow="hover" class="rounded-lg mb-4 bg-gradient-to-r from-blue-50 to-blue-100">
      <el-row :gutter="16" justify="space-between">
        <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
          <div class="flex items-center">
            <el-avatar :src="avatar" :size="70" class="mr-16px">
              <img src="@/assets/imgs/avatar.gif" alt="" />
            </el-avatar>
            <div>
              <div class="text-20px font-bold text-blue-700">
                {{ t('workplace.welcome') }} {{ username }}
              </div>
              <div class="mt-10px text-14px text-gray-500">
                祝您工作顺利，身体健康！
              </div>
            </div>
          </div>
        </el-col>
        <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
          <div class="h-70px flex items-center justify-end lt-sm:mt-10px">
            <div class="px-8px text-right">
              <div class="mb-16px text-14px text-gray-400 font-semibold">{{ t('收款单总量') }}</div>
              <CountTo
                class="text-20px text-blue-700"
                :start-val="0"
                :end-val="salesData.total"
                :duration="2600"
              />
            </div>
            <div class="px-8px text-right">
              <div class="mb-16px text-14px text-gray-400 font-semibold">{{ t('付款单总量') }}</div>
              <CountTo
                class="text-20px text-blue-700"
                :start-val="0"
                :end-val="financePayment.total"
                :duration="2600"
              />
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-row class="mt-8px" :gutter="8" justify="space-between">
      <el-col :xl="16" :lg="16" :md="24" :sm="24" :xs="24" class="mb-8px">
        <el-card shadow="hover" class="rounded-lg bg-gradient-to-r from-green-50 to-green-100">
          <template #header>
            <div class="h-3 flex justify-between">
              <span class="font-semibold text-blue-700">{{ t('产品') }}</span>
            </div>
          </template>
          <el-skeleton :loading="loading" animated>
            <el-row>
              <el-col
                v-for="(item, index) in inventory"
                :key="`inventory-${index}`"
                :xl="8"
                :lg="8"
                :md="8"
                :sm="24"
                :xs="24"
              >
                <el-card shadow="hover" class="mr-5px mt-5px rounded-lg border border-gray-300">
                  <div class="flex items-center">
                    <Icon :icon="item.icon" :size="25" class="mr-8px" />
                    <span class="text-16px font-medium text-blue-700">{{ item.name }}</span>
                  </div>
                  <div class="mt-12px text-9px text-gray-400">{{ t(item.description) }}</div>
                  <div class="mt-12px flex justify-between text-12px text-gray-400">
                    <span>{{ item.quantity }}</span>
                    <span>{{ formatTime(item.lastUpdated, 'yyyy-MM-dd') }}</span>
                  </div>
                  <div class="mt-12px text-12px text-gray-500">
                    <span>{{ t('保质期天数') }}: {{ item.expiryDay }}天</span>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-skeleton>
        </el-card>

        <el-card shadow="hover" class="mt-8px rounded-lg bg-gradient-to-r from-blue-50 to-blue-100">
          <el-skeleton :loading="loading" animated>
            <Echart :options="salesChartOptions" :height="280" />
          </el-skeleton>
        </el-card>
      </el-col>
      <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24" class="mb-8px">
        <el-card shadow="hover" class="rounded-lg bg-gradient-to-r from-green-50 to-green-100">
          <template #header>
            <div class="h-3 flex justify-between">
              <span class="font-semibold text-blue-700">{{ t('系统通知') }}</span>
            </div>
          </template>
          <el-skeleton :loading="loading" animated>
            <div v-for="(item, index) in announcements" :key="`announcement-${index}`">
              <div class="flex items-center">
                <el-avatar :src="avatar" :size="35" class="mr-16px">
                  <img src="@/assets/imgs/avatar.gif" alt="" />
                </el-avatar>
                <div>
                  <div class="text-14px font-medium text-blue-700">
                    <Highlight :keys="item.keys.map((v) => t(v))">
                      {{ item.type }} : {{ item.title }}
                    </Highlight>
                  </div>
                  <div class="mt-16px text-12px text-gray-400">
                    {{ formatTime(item.date, 'yyyy-MM-dd') }}
                  </div>
                </div>
              </div>
              <el-divider />
            </div>
          </el-skeleton>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'
import { formatTime } from '@/utils'
import { useUserStore } from '@/store/modules/user'
import { PurchaseInApi } from '@/api/erp/purchase/in'
import { FinanceReceiptApi } from '@/api/erp/finance/receipt'
import { FinancePaymentApi } from '@/api/erp/finance/payment'
import { ProductApi } from '@/api/erp/product/product'
import type { InventoryItem, Announcement } from './types'

defineOptions({ name: 'Home' })

const { t } = useI18n()
const userStore = useUserStore()
const loading = ref(true)
const avatar = userStore.getUser.avatar
const username = userStore.getUser.nickname

// 动态数据
const salesData = reactive({ total: 0 })
const financePayment = reactive({ total: 0 })
const inventory = reactive<InventoryItem[]>([])
const announcements = reactive<Announcement[]>([
  { title: '系统维护通知', type: '通知', keys: ['维护'], date: new Date() }
])

const salesChartOptions = reactive<EChartsOption>({
  title: { text: t('销售额统计'), left: 'center' },
  xAxis: { type: 'category', data: [] },
  yAxis: { type: 'value' },
  series: [{ data: [], type: 'line' }]
})

// 获取收款单总量信息
const getTotalSalesData = async () => {
  const response = await FinanceReceiptApi.getFinanceReceiptPage({ page: 1, size: 1 })
  console.log(response);
  if (response) {
    salesData.total = response.total || 0
  }
}

// 获取付款单总量信息
const getTotalFinancePaymentData = async () => {
  const response = await FinancePaymentApi.getFinancePaymentPage({ page: 1, size: 1 })
  console.log(response);
  if (response) {
    financePayment.total = response.total || 0
  }
}

// 获取产品信息
const getInventoryData = async () => {
  const response = await ProductApi.getProductPage({ page: 1, size: 5 })
  if (response && response.list) {
    inventory.splice(0, inventory.length, ...response.list)
  }
}

// 获取销售额统计信息
const getSalesChartData = async () => {
  const response = await FinanceReceiptApi.getFinanceReceiptPage({ page: 1, size: 5 })
  if (response && response.list) {
    const chartData = response.list.map(item => ({
      date: formatTime(item.receiptTime, 'yyyy-MM-dd'),
      value: item.receiptPrice
    }))
    
    set(salesChartOptions, 'xAxis.data', chartData.map(item => item.date))
    set(salesChartOptions, 'series[0].data', chartData.map(item => item.value))
  }
}

const loadData = async () => {
  await Promise.all([getTotalSalesData(),getTotalFinancePaymentData(),getInventoryData(), getSalesChartData()])
  loading.value = false
}

loadData()
</script>
